package com.egao.common.module.cms.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.egao.common.core.exception.ParameterException;
import com.egao.common.core.web.JsonResult;
import com.egao.common.core.web.PageParam;
import com.egao.common.module.cms.entity.Question;
import com.egao.common.module.cms.mapper.QuestionMapper;
import com.egao.common.module.cms.service.QuestionService;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 常见问题实现类
 * @author pyx
 */
@Service
public class QuestionServiceImpl extends ServiceImpl<QuestionMapper, Question> implements QuestionService {
    @Override
    public List<Question> listPage(PageParam<Question> pageParam) {
        return baseMapper.listPage(pageParam);
    }

    @Override
    public JsonResult insertQuestion(Question question) {
        if (question == null) {
            throw new ParameterException("参数对象为空");
        }

        if (question.getType() == null) {
            throw new ParameterException("类型不能为空");
        }
        if (StrUtil.isBlank(question.getTitle())) {
            throw new ParameterException("标题不能为空");
        }

        if (question.getSort() == null) {
            question.setSort(9999);
        }

        baseMapper.insert(question);
        return JsonResult.ok("添加成功");
    }

    @Override
    public JsonResult updateQuestion(Question question) {
        if (question == null) {
            throw new ParameterException("参数对象为空");
        }

        if (question.getType() == null) {
            throw new ParameterException("类型不能为空");
        }
        if (StrUtil.isBlank(question.getTitle())) {
            throw new ParameterException("标题不能为空");
        }

        baseMapper.updateById(question);
        return JsonResult.ok("修改成功");
    }

    @Override
    public JsonResult deleteQuestion(Integer id) {
        if (id == null) {
            throw new ParameterException("参数对象为空");
        }

        if (removeById(id)) {
            return JsonResult.ok("删除成功");
        }

        return JsonResult.error("删除失败");
    }

    @Override
    public JsonResult getId(Integer id) {
        if (id == null) {
            throw new ParameterException("参数对象为空");
        }

        QueryWrapper<Question> wrapper = new QueryWrapper<>();
        wrapper.eq("id", id);
        Integer count = baseMapper.selectCount(wrapper);

        if (count != 1) {
            throw new ParameterException("文章不存在");
        }

        Question question = baseMapper.selectById(id);
        return JsonResult.ok().setData(question);
    }
}
